__all__ = ['build_request_xml', 'parse_response_xml']

import xmltodict
from typing import Dict, Any, Optional
import xmltodict
from app.core.utils import generate_md5

def build_request_xml(data: Dict[str, Any], need_md5: bool = False) -> str:
    """
    构建请求 XML
    
    Args:
        data: 请求数据字典
        need_md5: 是否需要 MD5 签名
    
    Returns:
        XML 字符串
    """
    # 如果需要 MD5 签名，先生成签名
    if need_md5:
        # 按字段名排序，拼接字段值
        sorted_fields = sorted(data.keys())
        sign_str = "".join(str(data[field]) for field in sorted_fields if field != "md5")
        data["md5"] = generate_md5(sign_str)
    
    # 构建 XML
    request = {"request": data}
    return xmltodict.unparse(request, encoding="GBK", pretty=True)

def parse_response_xml(xml_str: str, verify_md5: bool = False) -> Dict[str, Any]:
    """
    解析响应 XML
    
    Args:
        xml_str: XML 字符串
        verify_md5: 是否验证 MD5 签名
    
    Returns:
        解析后的字典
    """
    # 解析 XML
    response = xmltodict.parse(xml_str)["response"]
    
    # 如果需要验证 MD5 签名
    if verify_md5 and "md5" in response:
        received_md5 = response.pop("md5")
        # 按字段名排序，拼接字段值
        sorted_fields = sorted(response.keys())
        sign_str = "".join(str(response[field]) for field in sorted_fields)
        calculated_md5 = generate_md5(sign_str)
        
        # 验证签名
        if received_md5 != calculated_md5:
            response["resp_code"] = "1020"  # MD5 签名错误
            response["error_msg"] = "MD5 签名验证失败"
    
    return response 